/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Com.TransaksiParkirdanLaporan.Com.Laporan;

import Com.TransaksiParkirdanLaporan.Com.Transaksi.DataParkir;
import Login.Karyawan;
import Login.Koneksi;
import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JMonthChooser;
import com.toedter.calendar.JYearChooser;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRTableModelDataSource;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Ardha
 */
public class LaporanController {

    private static javax.swing.JFrame frame;
    private static javax.swing.JDialog dialog = null;

    public static javax.swing.JFrame getFrame() {
        return frame;
    }

    public static void closeDialog() {
        LaporanController.dialog = null;
    }

    public static void openKeuanganHarianDialog(javax.swing.JFrame frame) {
        LaporanController.frame = frame;
        new LaporanKeuanganHarian(frame, true).setVisible(true);
    }

    public static void openKeuanganBulananDialog(javax.swing.JFrame frame) {
        LaporanController.frame = frame;
        if (LaporanController.dialog == null) {
            LaporanController.dialog = new LaporanKeuanganBulanan();
            dialog.setVisible(true);
        } else {
            dialog.show();
        }
    }

    public static void openLaporanFrame(javax.swing.JDialog dialog) {
        LaporanController.frame.setVisible(true);
        dialog.setVisible(false);
    }

    public static void showDateAndClock(final javax.swing.JLabel label) {
        /**
         *
         * @author Anonim, via search google.com
         */
        ActionListener taskPerformer = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent evt) {
                GregorianCalendar gc = new GregorianCalendar();
                SimpleDateFormat frmtDate = new SimpleDateFormat("dd-MMM-yyyy");

                String nol_jam = "", nol_menit = "", nol_detik = "";

                java.util.Date dateTime = new java.util.Date();
                int nilai_jam = dateTime.getHours();
                int nilai_menit = dateTime.getMinutes();
                int nilai_detik = dateTime.getSeconds();

                if (nilai_jam <= 9) {
                    nol_jam = "0";
                }
                if (nilai_menit <= 9) {
                    nol_menit = "0";
                }
                if (nilai_detik <= 9) {
                    nol_detik = "0";
                }

                String jam = nol_jam + Integer.toString(nilai_jam);
                String menit = nol_menit + Integer.toString(nilai_menit);
                String detik = nol_detik + Integer.toString(nilai_detik);

                label.setText(frmtDate.format(gc.getTime()) + ", "
                        + jam + " : " + menit + " : " + detik + " WIB");
            }
        };
        new Timer(1000, taskPerformer).start();
    }

    public static void laporanHarian(JDateChooser tanggal, JTable laporanTabel) throws Exception {
        TableCellRenderer kanan = new RenderingKanan();
        if (tanggal.getDate() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            String tanggal2 = sdf.format(tanggal.getDate());
            List<DataParkir> parkir = DataParkir.getConnection().getLaporanHarian(tanggal2);
            LaporanKeuanganHarianTabelModel model = new LaporanKeuanganHarianTabelModel(parkir);
            laporanTabel.setModel(model);
            if (laporanTabel.getRowCount() == 0) {
                throw new Exception("Tidak ada data transaksi pada tanggal masukan");
            } else {
                laporanTabel.getColumnModel().getColumn(2).setCellRenderer(kanan);
                laporanTabel.getColumnModel().getColumn(3).setCellRenderer(kanan);
            }
        }
    }

    public static void totalPendapatanHarian(JTable laporanTabel, JLabel totalPendapatan) {
        long total = 0;
        NumberFormat number = NumberFormat.getCurrencyInstance();

        for (int i = 0; i < laporanTabel.getRowCount(); i++) {
            String pendapatan = laporanTabel.getValueAt(i, 3).toString().substring(2).replace(".", "").replace(",00", "");
            total = total + (Long.parseLong(pendapatan));
        }
        totalPendapatan.setText(number.format(total));
    }

    public static void totalKendaraanHarian(JTable laporanTabel, JLabel totalKendaraan) {
        long total = 0;
        total = laporanTabel.getRowCount();
        totalKendaraan.setText(String.valueOf(total));
    }

    public static void laporanBulanan(JTable table, JMonthChooser month, JYearChooser year,
            JLabel totalKendaraanLabel, JLabel totalPendapatanLabel)
            throws SQLException, FileNotFoundException, IOException, Exception {
        String bulan = String.valueOf(month.getMonth() + 1);
        String tahun = String.valueOf(year.getYear());
        String tanggal = bulan + "-" + tahun;
        Connection conn = Koneksi.getDBConnection();
        String sqlTanggal = "select distinct tanggalrekap from datarekap "
                + "where to_char(tanggalrekap,'MM-yyyy')=(?) order by tanggalrekap";
        PreparedStatement psmt = conn.prepareStatement(sqlTanggal);
        psmt.setObject(1, tanggal);
        ResultSet rset = psmt.executeQuery();
        List list = new ArrayList();
        int index = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        while (rset.next()) {
            list.add(sdf.format(rset.getDate(1)));
        }
        LinkedList dataTransaksi = new LinkedList();
        Object[] c = list.toArray();
        String sqlData = "select(select sum(jumlahkendaraanpershift) "
                + "from datarekap where to_char(tanggalrekap,'dd-MM-yyyy')=(?))"
                + " as kendaraan, (select sum(jumlahhelm) from dataparkir "
                + "where to_char(tanggalkeluar,'dd-MM-yyyy')=(?)) as helm, "
                + "(select sum(jumlahpendapatanpershift)"
                + " from datarekap where to_char(tanggalrekap,'dd-MM-yyyy')=(?)) "
                + "as pendapatan  from dual";
        for (int i = 0; i < c.length; i++) {
            String tanggalTransaksi = String.valueOf(c[i]);
            PreparedStatement psmt2 = conn.prepareStatement(sqlData);
            psmt2.setObject(1, tanggalTransaksi);
            psmt2.setObject(2, tanggalTransaksi);
            psmt2.setObject(3, tanggalTransaksi);
            ResultSet rset2 = psmt2.executeQuery();
            while (rset2.next()) {
                int totalKendaraan = rset2.getInt(1);
                int totalHelm = rset2.getInt(2);
                long totalPendapatan = rset2.getLong(3);
                dataTransaksi.add(tanggalTransaksi);
                dataTransaksi.add(totalKendaraan);
                dataTransaksi.add(totalHelm);
                dataTransaksi.add(totalPendapatan);
            }
        }

        Object[] dataTrans = dataTransaksi.toArray();
        String[] kolom = {"Tanggal Transaksi", "Jumlah Kendaraan", "Jumlah Helm", "Total Pendapatan"};
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(kolom);
        if (dataTrans.length == 0) {
            table.setModel(new javax.swing.table.DefaultTableModel(
                    new Object[][]{
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null}
                    },
                    new String[]{"Tanggal Transaksi", "Jumlah Kendaraan", "Jumlah Helm", "Total Pendapatan"}));
            totalKendaraanLabel.setText("0");
            totalPendapatanLabel.setText("RP 0,00");
            throw new Exception("Tidak ada data pada bulan dan tahun masukan");
        } else {
            NumberFormat numFormat = NumberFormat.getCurrencyInstance();
            while (!dataTransaksi.isEmpty()) {
                String[] data = new String[4];
                for (int i = 0; i < 4; i++) {
                    if (i == 3) {
                        Object temporary = dataTransaksi.remove();
                        if (String.valueOf(temporary).matches("0")) {
                            data[i] = "Rp0,00";
                        } else {
                            data[i] = numFormat.format(temporary);
                        }
                    } else {
                        data[i] = String.valueOf(dataTransaksi.remove());
                    }
                }
                model.addRow(data);
            }
            table.setModel(model);
            TableCellRenderer kanan = new RenderingKanan();
            table.getColumnModel().getColumn(1).setCellRenderer(kanan);
            table.getColumnModel().getColumn(2).setCellRenderer(kanan);
            table.getColumnModel().getColumn(3).setCellRenderer(kanan);
            long totalKendaraan = 0;
            long totalPendapatan = 0;
            for (int i = 0; i < table.getRowCount(); i++) {
                String totKendaraan, totPendapatan;
                totKendaraan = table.getValueAt(i, 1).toString();
                totPendapatan = table.getValueAt(i, 3).toString().substring(2).replace(".", "").replace(",00", "");
                totalKendaraan = totalKendaraan + (Long.parseLong(totKendaraan));
                totalPendapatan = totalPendapatan + (Long.parseLong(totPendapatan));
            }
            totalKendaraanLabel.setText(String.valueOf(totalKendaraan));
            totalPendapatanLabel.setText(String.valueOf(totalPendapatan));
        }
    }

    public static void cetakLaporan(JButton button, JTable table, JDialog dialog, JLabel kendaraan, JLabel pendapatan) {
        try {
            String nama = null, idKaryawan = null, jabatan = null;
            List<Karyawan> kTest = Karyawan.getKoneksiKontrol().getDataKaryawan(Karyawan.getusrID());
            for (Karyawan k : kTest) {
                nama = k.getLastName() + ", " + k.getFirstName();
                idKaryawan = k.getUsername();
                jabatan = k.getJabatan();
            }
            String reportSource = "./reports/LaporanBulanan.jasper";
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("namaStaff", nama);
            params.put("IDStaff", idKaryawan);
            params.put("totalPendapatan", String.valueOf(pendapatan.getText()));
            params.put("totalKendaraan", String.valueOf(kendaraan.getText()));
            params.put("jabatan", jabatan);
            JasperPrint jasperPrint = JasperFillManager.fillReport("./reports/LaporanBulanan.jasper", params, new JRTableModelDataSource(table.getModel()));
            button.setEnabled(false);
            JasperViewer.viewReport(jasperPrint, false);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(dialog, ex.getMessage());
        }
    }
}
